package top.vanchor.myblog2back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import top.vanchor.myblog2back.entity.BackAuthGroup;
import top.vanchor.myblog2back.entity.BackAuthGroupRule;
import top.vanchor.myblog2back.mapper.BackAuthGroupRuleMapper;
import top.vanchor.myblog2back.service.IBackAuthGroupRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Ding
 * @since 2022-01-27
 */
@Service
public class BackAuthGroupRuleServiceImpl extends ServiceImpl<BackAuthGroupRuleMapper, BackAuthGroupRule> implements IBackAuthGroupRuleService {

    @Resource
    private BackAuthGroupRuleMapper mapper;

    @Override
    public List<BackAuthGroupRule> getIdsByGroupId(Integer groupId) {
        QueryWrapper<BackAuthGroupRule> wrapper = new QueryWrapper<>();
        wrapper.eq("group_id",groupId);
        return mapper.selectList(wrapper);
    }

    @Override
    public List<Integer> getRuleIdsByGroupId(Integer groupId) {
        //保留，但不应用，采用mysql
//        QueryWrapper<BackAuthGroupRule> wrapper = new QueryWrapper<>();
//        wrapper.eq("group_id",groupId)
//                .select("rule_id");
//        List<BackAuthGroupRule> listTemp = mapper.selectList(wrapper);
//        List<Integer> ids = new ArrayList<>();
//        for (BackAuthGroupRule backAuthGroupRule : listTemp) {
//            ids.add(backAuthGroupRule.getRuleId());
//        }
        return mapper.getRuleIdsByGroupIdNotIncludeTopId(groupId);
    }

    @Override
    public int doRulesEdit(Integer groupId, List<Integer> ruleIds) {
        //先删除
        QueryWrapper<BackAuthGroupRule> wrapper = new QueryWrapper<>();
        wrapper.in("group_id",groupId);
        mapper.delete(wrapper);
        //再添加
        for (Integer ruleId : ruleIds) {
            BackAuthGroupRule bean = new BackAuthGroupRule();
            bean.setGroupId(groupId);
            bean.setRuleId(ruleId);
            mapper.insert(bean);
        }
        return ruleIds.size();
    }
}
